
package com.toman.ui.work.workplan;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshScrollView;
import com.king.zxing.CaptureActivity;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.request.GetRequest;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DeviceHouseProductReportEntity;
import com.toman.JavaBean.StaticsCount;
import com.toman.R;
import com.toman.Util.ActionCallback;
import com.toman.Util.BaseNetUtil;
import com.toman.Util.DialogUtils;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.DialogBean;
import com.toman.toolbar.ToolBarActivity;
import com.toman.ui.work.workshop.ChangeWheelAddActivity;
import com.toman.ui.work.workshop.ChangeWheelInfActivity;
import com.toman.widget.ClearEditText;
import com.toman.widget.callback.StringLoadingCallback;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

import static com.toman.Interfaces.NewBaseUrl.SCANNING_CODE;

public class WorkshopSubmitActivity extends ToolBarActivity {
    CommonAdapter<DeviceHouseProductReportEntity> adapter;
    private List<DeviceHouseProductReportEntity> list = new ArrayList<>();

    @BindView(R.id.et_search)
    ClearEditText etSearch;
    @BindView(R.id.tv_select)
    TextView tvSelect;
    @BindView(R.id.fl_et)
    RelativeLayout flEt;
    @BindView(R.id.tv_select0)
    TextView tvSelect0;
    @BindView(R.id.iv_select0)
    ImageView ivSelect0;
    @BindView(R.id.rl_select0)
    RelativeLayout rlSelect0;
    @BindView(R.id.tv_select1)
    TextView tvSelect1;
    @BindView(R.id.iv_select1)
    ImageView ivSelect1;
    @BindView(R.id.rl_select1)
    RelativeLayout rlSelect1;
    @BindView(R.id.ll_base)
    LinearLayout llBase;
    @BindView(R.id.cb_muti)
    CheckBox cbMuti;
    @BindView(R.id.btn_muti)
    Button btnMuti;
    @BindView(R.id.rl_muti)
    RelativeLayout rlMuti;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.mPullToRefreshScrollView)
    PullToRefreshScrollView mPullToRefreshScrollView;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_workshop_submit);
        ButterKnife.bind(this);

        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        super.onResume();
        if (!StringUtils.isEmpty(getIntent().getStringExtra("status"))) {
            p_id = (getIntent().getStringExtra("etSearch"));
            setStatus(getIntent().getStringExtra("status"));
        }
        else {setStatus("0");}

    }
//
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.toolbar_add_scan, menu);
//        MenuItem menuItem = menu.findItem(R.id.menu_scan);
//        MenuItem menuItem2 = menu.findItem(R.id.menu_add);
//        menuItem.setVisible(false);
//
//        if (!PermissonUtils.contains(this, baseEnum.has(PermEnum.ADD))) {
//            menuItem.setVisible(false);
//            menuItem2.setVisible(false);
//        }
//
//        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                switch (item.getItemId()) {
//                    case R.id.menu_add:
////                        Bundle bundle = new Bundle();
////                        bundle.putString("id", getIntent().getStringExtra("id"));
//                        IntentUtils.startActivity(WorkshopSubmitActivity.this, SubmitPlanAddActivity.class);
//
//                        break;
//
//                    case R.id.menu_scan:
//                        if (ViewUtil.checkPer(WorkshopSubmitActivity.this)) {
//                            Intent intent = new Intent(WorkshopSubmitActivity.this, CaptureActivity.class);
//                            startActivityForResult(intent, SCANNING_CODE);
//                        }
//                        break;
//                }
//                return false;
//            }
//        });
//
//        return true;
//    }

    private void initView() {
        baseEnum=BaseEnum.WORKSHOPSUBMIT;
        initToolBar(baseEnum.name);
        etSearch.setHint("产线名称");
//        ViewUtil.permission(getApplicationContext(),BaseEnum.FIRSTINSPECTION.has(PermEnum.CHECK),rlMuti);
        initAdapter();
        cbMuti.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setCheckStatus(b);
                }
                adapter.notifyDataSetChanged();
            }
        });
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<DeviceHouseProductReportEntity> beanlist = adapter.getDatas();
                DeviceHouseProductReportEntity bean = beanlist.get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", bean);
                bundle.putString("status", bean.getAuditStatus());
                IntentUtils.startActivity(WorkshopSubmitActivity.this, SubmitPlanEditActivity.class, bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        lv.setAdapter(adapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
        };
        lv.setLayoutManager(linearLayoutManager);
        mPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                dialog=null;
                dialogList.clear();
                page = 2;
                customer(1, 1, etSearch.getText().toString().trim());
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                customer(page, 2, etSearch.getText().toString().trim());
                page += 1;


            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                customer(1, 1, s.toString().trim());

            }
        });
    }

    private void initAdapter() {
        adapter = new CommonAdapter<DeviceHouseProductReportEntity>(this, R.layout.reuse_list_workshop, list) {
            @Override
            protected void convert(ViewHolder holder, DeviceHouseProductReportEntity item, final int position) {
//                holder.setText(R.id.tv_code, item.getSendworkorderEntity().getSendworkCode());
                CheckBox checkBox = holder.getView(R.id.cb_status);
                checkBox.setChecked(item.getCheckStatus());
                checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> item.setCheckStatus(isChecked));
                TextView tv_time = holder.getView(R.id.tv_time);
                TextView tv_title5 = holder.getView(R.id.tv_title5);
                TextView tv_man = holder.getView(R.id.tv_content5);
                holder.getView(R.id.tv_code).setVisibility(View.GONE);
                holder.getView(R.id.iv_status).setVisibility(View.GONE);
                holder.setText(R.id.tv_title1, "部门名称");
                holder.setText(R.id.tv_content1, item.getDepartmentName());
                holder.setText(R.id.tv_title2, "产线名称");
                holder.setText(R.id.tv_content2, item.getBeltlineName());
                holder.setText(R.id.tv_title3, "日期");
                holder.setText(R.id.tv_content3, item.getDay() + "");
                holder.setText(R.id.tv_title4, "产线计划数");
                holder.setText(R.id.tv_content4, item.getBeltlinePlanOutput() + "");

                holder.getView(R.id.ll_6).setVisibility(View.VISIBLE);


                holder.getView(R.id.btn_del).setVisibility(View.VISIBLE);
                holder.getView(R.id.btn_del).setOnClickListener(v -> BaseNetUtil.actionDialog(WorkshopSubmitActivity.this, NewBaseUrl.devicehouseproductreport_delete, item.getId() + "", token, "删除" + baseEnum.name, () -> customer(1, 1, etSearch.getText().toString())));
                ViewUtil.permissionNew(getApplicationContext(), baseEnum.has(PermEnum.DELETE),   holder.getView(R.id.btn_del));
//                holder.getView(R.id.btn_check).setOnClickListener(v -> CheckDialog(ChangeWheelActivity.this,"首件质检","",item));
//       holder.getView(R.id.tv_title6).setVisibility(View.GONE);
//                holder.getView(R.id.tv_content6).setVisibility(View.GONE);
                switch (item.getAuditStatus()) {
                    case "0":
                        holder.setText(R.id.tv_title5, "提交完工数");
                        holder.setText(R.id.tv_content5, item.getFinishCount() + "");
                        checkBox.setVisibility(View.VISIBLE);
                        holder.setText(R.id.tv_title6, "报工人");
                        holder.setText(R.id.tv_content6, item.getCreateUserName());
                        tv_time.setText(item.getCreateTime());
                        Button button = holder.getView(R.id.btn_check);
                        button.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("bean", item);
                                IntentUtils.startActivity(WorkshopSubmitActivity.this, SubmitPlanCheckActivity.class, bundle);                            }
                        });
                        ViewUtil.permissionNew(getApplicationContext(), baseEnum.has(PermEnum.CHECK), button);
                        break;
                    case "1":
                        holder.setText(R.id.tv_title5, "审核完工数");
                        holder.setText(R.id.tv_content5, item.getVerifyFinishCount() + "");
                        checkBox.setVisibility(View.GONE);
                        holder.setText(R.id.tv_title6, "审核人");
                        holder.setText(R.id.tv_content6, item.getAuditUserName());
                        tv_time.setText(item.getAuditTime());
                        button = holder.getView(R.id.btn_check);
                        button.setVisibility(View.GONE);
                        break;

                }
            }
        };
    }

    public void customer(Integer page, final Integer type, String search) {
        if (dialog != null) {
            dialog.dismiss();
        }
        GetRequest params = OkHttpUtils
                .get(NewBaseUrl.devicehouseproductreport_list)
                .params("token", token)
                .params("key", search)
                .params("limit", NewBaseUrl.num)
                .params("page", page.toString())
                .params("auditStatus", status)
                .params("id",p_id)
                ;

        for (DialogBean bean: dialogList){
            params.params(bean.getSubmitName(),bean.getResult());
        }
                params.execute(new StringLoadingCallback(this,mPullToRefreshScrollView,search) {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", getClass() + ": " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");

                            List<DeviceHouseProductReportEntity> jsonArray = new ArrayList<DeviceHouseProductReportEntity>(JsonExcludeNull.parseArrayExcludeNull(Jpage.getString("list"), DeviceHouseProductReportEntity.class));
                            list.addAll(jsonArray);

                            if (list.size() == 0) {
                                mMangeNodata.setVisibility(View.VISIBLE);
                            } else {
                                mMangeNodata.setVisibility(View.GONE);
                            }
                            adapter.notifyDataSetChanged();
                            StaticsCount count = JSON.parseObject(Jpage.getString("staticsCount"), new TypeReference<StaticsCount>() {
                            });
                            tvSelect0.setText("待审核(" + count.getCount0() + ")");
                            tvSelect1.setText("已审核(" + count.getCount1() + ")");
setCbMuti();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                        mPullToRefreshScrollView.onRefreshComplete();
                    }
                });
    }


    private void setStatus(String status) {
        this.status = status;
        cbMuti.setChecked(false);
        switch (status) {
            case "0":
                tvSelect0.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect1.setTextColor(getResources().getColor(R.color.black33));

                ivSelect0.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.white));
                customer(1, 1, etSearch.getText().toString());
//                ViewUtil.permissionNew(getApplicationContext(), baseEnum.has(PermEnum.CHECK), rlMuti);

                break;
            case "1":
                tvSelect1.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect0.setTextColor(getResources().getColor(R.color.black33));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.white));
//                rlMuti.setVisibility(View.GONE);

                customer(1, 1, etSearch.getText().toString());
                break;

        }
    }
    private void setCbMuti(){
        switch (status){
            case "0":
                ViewUtil.permissionNew(getApplicationContext(), baseEnum.has(PermEnum.CHECK),list, rlMuti);

                cbMuti.setChecked(false);
                break;
            case "1":
                rlMuti.setVisibility(View.GONE);

                break;

        }
    }
    @OnClick({R.id.rl_select0, R.id.rl_select1, R.id.btn_muti})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_select0:
                setStatus("0");
                break;
            case R.id.rl_select1:
                setStatus("1");
                break;
            case R.id.btn_muti:
                if (ViewUtil.getMutiCheck(list) == null) {
                    ToastUtil.makeText(getApplicationContext(), "请至少选中一个选项");
                } else {
                    switch (status) {
                        case "0":
                            DialogUtils.mutiCheckDialog(this, baseEnum.name, "批量审核", NewBaseUrl.devicehouseproductreport_audit, ViewUtil.getMutiCheck(list), new ActionCallback() {
                                @Override
                                public void run() {
                                    customer(1, 1, etSearch.getText().toString());
                                }
                            });
                            break;

                    }

                }
                break;
        }
    }
    @OnClick(R.id.tv_select)
    public void onViewClicked() {
        showDialog();

    }
    public void showDialog() {
        if (dialog == null) {
            dialogList.clear();
            dialogList.add( new DialogBean("departmentId","部门名称", 1, BaseNetUtil.base(this, NetworkEnum.DEP, mCompanyId)));
            dialogList.add( new DialogBean("beltlineId","产线名称", 1, BaseNetUtil.base(this, NetworkEnum.BELTLINE, mCompanyId)));
            dialogList.add( new DialogBean("day","日期", 2));

            dialog = DialogUtils.selectNewDialog(this, dialogList, new ActionCallback() {
                @Override
                public void run() {
                    customer(1, 1,"");
                    dialog.dismiss();

                }
            });
            dialog.show();
        } else {
            dialog.show();
        }
    }
}
